Thread: Malloc doubt

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    38

    Malloc doubt

    Hello everyone.

    I have a little doubt about freeing allocated memory. I'm using this two functions.

    Code:
    gchar* status_code (gchar *status)
    {
    	gchar* data = "";
    	
    	status ++;		
    	while (*status != CR && *(status+1) != LF)
    	{
    		data = concatenar_char(data,status);
    		status ++;		
    	}
    
    	return data;
    }/*status_code*/
    
    gchar * concatenar_char (gchar* str1, gchar* str2)
    {
    	gchar *result;
    	if ( str2 != NULL )
    	{
    		result = (gchar *)malloc(strlen(str1) + sizeof(gchar) + 1);
    		if ( result != NULL )
    		{
    			strcpy(result, str1);
    			strncat(result, str2, 1);
    		}
    	}
    	return result;
    }/*concatenar_char*/
    In the second function I cant free result before return it. So where can I free the allocated memory (result) without getting an error from the compiler??

    Is there a better way to do this?

    Thanks in advance.
    Last edited by guillermoh; 09-09-2007 at 07:27 PM. Reason: Mistakes

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    So where can I free the allocated memory (result) without getting an error from the compiler??
    anywhere after you call concatenar_char. in main, for example.

    what's the error?

    what's LF?

  3. #3
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    It wont make any sense if you free the result before you return result in the function. The main idea in that function is to concatenate two string and return the result string. If you free of the string in the function itself, you cant retrieve any results from the calling function.

    ssharish

  4. #4
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Code:
    result = (gchar *)malloc(strlen(str1) + sizeof(gchar) + 1);
    Looks suspicious to me. Maybe?
    Code:
    result = malloc(strlen(str1) + strlen(str2) + 1);
    Last edited by prog-bman; 09-09-2007 at 09:31 PM.

  5. #5
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc doubt
    By edesign in forum C Programming
    Replies: 17
    Last Post: 04-09-2010, 03:48 PM
  2. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  3. Is there a limit on the number of malloc calls ?
    By krissy in forum Windows Programming
    Replies: 3
    Last Post: 03-19-2006, 12:26 PM
  4. Malloc and calloc problem!!
    By xxhimanshu in forum C Programming
    Replies: 19
    Last Post: 08-10-2005, 05:37 AM
  5. malloc() & address allocation
    By santechz in forum C Programming
    Replies: 6
    Last Post: 03-21-2005, 09:08 AM